package com.d3works.apps.production.service;

import com.d3works.apps.ReportFactory;
import com.d3works.apps.base.db.repo.SequenceRepository;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.production.db.RawMaterialRequirement;
import com.d3works.apps.production.exceptions.ProductionExceptionMessage;
import com.d3works.apps.production.report.IReport;
import com.d3works.apps.report.engine.ReportSettings;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;

public class RawMaterialRequirementServiceImpl implements RawMaterialRequirementService {

  /** The title of the report. */
  public static final String RAW_MATERIAL_REPORT_TITLE = "Raw material requirement";

  @Override
  public String print(RawMaterialRequirement rawMaterialRequirement) throws D3worksException {
    String name = String.format("%s - ${date}", I18n.get(RAW_MATERIAL_REPORT_TITLE));
    ReportSettings reportSetting =
        ReportFactory.createReport(IReport.RAW_MATERIAL_REQUIREMENT, name);

    String locale = ReportSettings.getPrintingLocale(null);
    return reportSetting
        .addParam("RawMaterialRequirementId", rawMaterialRequirement.getId())
        .addParam(
            "Timezone",
            rawMaterialRequirement.getCompany() != null
                ? rawMaterialRequirement.getCompany().getTimezone()
                : null)
        .addParam("Locale", locale)
        .generate()
        .getFileLink();
  }

  @Override
  public String getSequence(RawMaterialRequirement rawMaterialRequirement) throws D3worksException {

    String seq =
        Beans.get(SequenceService.class)
            .getSequenceNumber(
                SequenceRepository.RAW_MATERIAL_REQUIREMENT,
                rawMaterialRequirement.getCompany(),
                RawMaterialRequirement.class,
                "code");
    if (seq == null) {
      throw new D3worksException(
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          I18n.get(ProductionExceptionMessage.RAW_MATERIAL_REQUIREMENT_NO_SEQUENCE),
          rawMaterialRequirement.getCompany().getName());
    }

    return seq;
  }
}
